<?php

namespace App\Http\Validators;

use Illuminate\Support\Facades\Validator;

abstract class Validate
{

	//被验证的规则
	protected $checkRules = [];

	//验证场景
	protected $sceneType = '';

	//验证规则
	protected $rule = [];

	//错误信息
	protected $message = [];

	//场景信息
	protected $scene = [];

	///错误信息
	protected $errorInfo = [];

	/**
	 * 设置场景
	 * @param $type
	 * @return $this
	 */
	public function scene($type)
	{
		if (array_key_exists($type, $this->scene)) {
			$this->sceneType = $type;
		} else {
			$this->sceneType = '';
		}
		return $this;
	}

	/**
	 * 获取检测的规则
	 * @return array
	 */
	protected function getCheckRule()
	{
		if ($this->sceneType) {
			foreach ($this->scene[$this->sceneType] as $key => $value) {
				if (isset($this->rule[$value])) {
					$this->checkRules[$value] = $this->rule[$value];
				}
			}
		} else {
			$this->checkRules = $this->rule;
		}

		return $this->checkRules;
	}

	/**
	 * 检测是否符合规则
	 * @param $data
	 * @return bool
	 */
	public function check($data)
	{
		$validator = Validator::make($data, $this->getCheckRule(), $this->message);
		if ($validator->fails()) {
			$this->errorInfo = $validator->errors()->all();
			return false;
		}
		$this->errorInfo = "";
		return true;
	}

	/**
	 * 获取错误信息
	 * @return array
	 */
	public function getError()
	{
		return $this->errorInfo;
	}
}
